<template>
  <div class="public-homepage-detail app-container">
    <div class="public-homepage-top">
      <div v-if="$route.query.action === 'add'">新增</div>
      <div v-else-if="$route.query.action === 'edit'">编辑</div>
      <div v-else-if="$route.query.action === 'detail'">详情</div>
      <div class="action-btn-box" v-if="$route.query.action !== 'detail'">
        <el-button
          type="primary"
          plain
          size="mini"
          @click="handleAdd"
        >确定</el-button>
        <el-button
          plain
          size="mini"
          @click="goBack"
        >取消</el-button>
      </div>
      <div class="action-btn-box" v-else>
        <el-button
          plain
          size="mini"
          @click="goBack"
        >返回</el-button>
      </div>
    </div>
    <div class="public-homepage-content">
      <div class="public-homepage-left">
        <div class="detail-title">首页图片信息</div>
        <el-form :model="queryParams" :rules="rules" label-position="top" ref="queryForm" label-width="78px">
          <el-form-item label="类型" prop="imgType">
            <el-select
              v-model="queryParams.imgType"
              placeholder="类型"
              :disabled="$route.query.action === 'detail'"
              clearable
              size="small"
              style="width: 240px"
            >
              <el-option
                v-for="dict in typeList"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
          <!-- <el-form-item label="关联景区" prop="jingquId" v-if="queryParams.imgType == '1'"> -->
          <el-form-item label="关联景区" prop="jingquId">
            <el-select
              :disabled="$route.query.action === 'detail'"
              v-model="queryParams.jingquId"
              placeholder="关联景区"
              clearable
              filterable
              size="small"
              style="width: 240px"
            >
                <el-option 
                label="不关联任何景区" :value="0">
                </el-option>
                <el-option v-for="item in jingQuList" :key="item.value"
                :label="item.label" :value="item.value">
                </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="状态" prop="imgStatus">
            <el-switch
              :disabled="$route.query.action === 'detail'"
              v-model="queryParams.imgStatus"
              active-color="#ccc"
              :active-value="'0'"
              :inactive-value="'1'"
              inactive-color="#3370FF"
              >
            </el-switch>
          </el-form-item>
          <el-form-item label="图片" required>
            <div class="upload-box">
              <div class="file-box-view">
                <el-image
                  v-if="queryParams.imgUrl"
                  :src="queryParams.imgUrl"
                  :preview-src-list="[queryParams.imgUrl]"
                >
                </el-image>
              </div>
              <el-upload
                  v-if="$route.query.action !== 'detail'"
                  :action="uploadUrl"
                  list-type="picture-card"
                  :before-upload="handleBeforeUpload"
                  :on-success="(response) => handleUploadSuccess('imgUrl', response)"
                  :on-error="handleUploadError"
                  :headers="headers"
                  :show-file-list="false"
                >
                  <i class="el-icon-plus"></i>
              </el-upload>
            </div>
          </el-form-item>
        </el-form>
      </div>
      <div class="public-homepage-right">
        <div class="detail-title">首页图片信息</div>
        <div class="img-box">
          <img v-show="queryParams.imgUrl" :src="queryParams.imgUrl" alt="">
          <div></div>
        </div>
      </div>
    </div>

  </div>
</template>

<script>
import { updateFn, add, list } from "@/api/publicService/homepage";
import { getToken } from "@/utils/auth";
import {
  jingQuListApi, // 获取所有景区列表
} from "@/api/YApi/scenicSpot";

export default {
  name: "Logininfor",
  data() {
    return { 
      rules: {
          imgType: [
            { required: true, message: '请选择类型', trigger: 'change' }
          ],
          jingquId: [
            { required: true, message: '请选择景区', trigger: 'change' }
          ],
          imgStatus: [
            { required: true, message: '请选择状态', trigger: 'change' }
          ],
      },
      // 遮罩层
      loading: true,
      uploadUrl: window.serverAPI.url + "/common/upload", // 上传的图片服务器地址
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      typeList: [],
      jingQuList: [],
      // 导出遮罩层
      exportLoading: false,
      // 查询参数
      queryParams: {
        jingquId: undefined,
        imgType: undefined,
        imgStatus: undefined,
        imgUrl: undefined,
      }
    };
  },
  created() {
    this.getJingQuList()
    this.$route.query.id && this.getList();
    this.getDicts("shouye_img_type").then(response => {
      this.typeList = response.data;
    });
  },
  methods: {
    getList() {
      let {pageNum, pageSize, imgStatus, imgType, startTime, endTime, id} = this.$route.query
      list({
        pageNum, pageSize, imgStatus, imgType, startTime, endTime
      }).then(res => {
        let arr = res?.data?.rows || []
        let currentObj = arr.filter(item => item.id == id)?.[0] || {};
        console.log(currentObj);
        this.queryParams = {
          jingquId: Number(currentObj?.jingquId) || 0,
          imgType: currentObj?.imgType || undefined,
          imgStatus: currentObj?.imgStatus || undefined,
          imgUrl: currentObj?.imgUrl || undefined,
        };

      });
    },
    // 景区列表
    getJingQuList() {
      jingQuListApi()
        .then((res) => {
          if (res.code === 200) {
            this.jingQuList = res.data.map((v) => {
              return {
                value: v.jingquId,
                label: v.jingquName,
              };
            });
          }
        })
    },
    // 使用 before-upload 限制用户上传的图片格式和大小。
    handleBeforeUpload(file) {
      // 校检文件大小
      const isLt = file.size / 1024 / 1024 < 8;
      if (!isLt) {
        this.$message.error(`上传文件大小不能超过8MB!`);
        return false;
      }
      // 检验格式
      let type = file.type;
      let jpg = type.indexOf("jpg");
      let png = type.indexOf("png");
      let jpeg = type.indexOf("jpeg");
      if (jpg == -1 && png == -1 && jpeg == -1) {
        this.$message.error(`上传文件格式为jpg，png，jpeg!`);
        return false;
      }

      return true;
    },

    // 文件上传成功钩子
    handleUploadSuccess(param, response) {
      if (response.code === 200) {
        this.queryParams[param] = response.data.url
      }
    },

    // 删除已上传的文件
    onRemoveHandel(param) {
      this.queryParams[param] = ''
    },

    // 文件上传失败
    handleUploadError() {
      this.$message.error("图片插入失败");
    },
    handleAdd() {
      this.$refs.queryForm.validate((tag) => {
        if (tag) {
          let imgArr = ['imgUrl']
          let arr = imgArr.filter(item => this.queryParams[item])
          if (arr.length !== 1) {
            return this.$message.error("请上传图片");
          } else {
            let fun = this.$route.query.id ? updateFn : add
            fun({
              id: this.$route.query?.id || undefined,
              ...this.queryParams,
              jingquId: this.queryParams.jingquId || undefined
            }).then(res => {
              if (res?.code === 200) {
                this.$message.success("保存成功");
                this.goBack();
              } else {
                this.$message.error(res?.msg);
              }
            })
          }
        }
      });
    },
    goBack() {
      this.$router.go(-1);
    },
  }
};
</script>


<style rel="stylesheet/scss" lang="scss">
.public-homepage-detail {
  .public-homepage-top {
    border-bottom: 1px solid #F2F3F5;
    display: flex;
    justify-content: space-between;
    padding: 12px;
    align-items: center;
  }
  .public-homepage-content {
    display: flex;
    .detail-title {
      position: relative;
      padding-left: 12px;
      padding-block: 20px;
      &::after {
        content: '';
        width: 4px;
        height: 16px;
        background: #3370FF;
        position: absolute;
        left: 0;
        top: 0;
        bottom: 0;
        margin: auto 0;

      }
    }
    .public-homepage-left {
      flex: 2;
      border-right: 1px solid #F2F3F5;
      margin-right: 30px;
    }
    .public-homepage-right {
      flex: 1;
    }
    .img-box {
      width: 307px;
      height: 650px;
      position: relative;
      border-radius: 24px;
      border: 3px solid #000;
      div {
        position: absolute;
        width: 70px;
        height: 20px;
        background: #000;
        border-radius: 10px;
        left: 0;
        right: 0;
        top: 10px;
        margin: 0 auto;
      }
      img {
        width: 100%;
        height: 100%;
      }
    }
  }
  .upload-box {
    display: flex;
    .file-box-view{
      height: 146px;
      width: 146px;
      margin-right: 10px;
      display: flex;
      justify-content: center;
      align-items: center;
      img{
        max-height: 100px;
        max-width: 100px;
      }
    }
  }
}
</style>